import React, {useEffect, useState, useCallback} from 'react';
import {Button, Card, Col, Input, message, Row, Select, Space, Statistic, Table} from 'antd';
import {ExportOutlined, ReloadOutlined, SearchOutlined} from '@ant-design/icons';
import {shipmentsAPI, uploadDataAPI} from '../../services/api';
import './ShipmentsPage.css';

const ShipmentsPage = () => {
    const [shipments, setShipments] = useState([]);
    const [loading, setLoading] = useState(false);
    const [dataId, setDataId] = useState('');
    const [batchList, setBatchList] = useState([]);
    const [originSearch, setOriginSearch] = useState(''); // eslint-disable-next-line
    const [destinationSearch, setDestinationSearch] = useState(''); // eslint-disable-next-line
    const [stats, setStats] = useState({
        total: 0,
        pending: 0,
        inTransit: 0,
        delivered: 0
    });

    // 获取货物数据 - 必须提供dataId
    const fetchShipments = async (currentDataId) => {
        if (!currentDataId) {
            message.warning('请先选择批次');
            return;
        }

        setLoading(true);
        try {
            const response = await shipmentsAPI.getByDataId(currentDataId);
            // response已经是data部分，确保是数组
            let data = Array.isArray(response) ? response : [];

            // 起始节点筛选
            if (originSearch.trim()) {
                data = data.filter(shipment =>
                    String(shipment.originNode || '').toLowerCase().includes(originSearch.toLowerCase().trim())
                );
            }

            // 目标节点筛选
            if (destinationSearch.trim()) {
                data = data.filter(shipment =>
                    String(shipment.destinationNode || '').toLowerCase().includes(destinationSearch.toLowerCase().trim())
                );
            }

            setShipments(data);

            // 计算统计数据
            const stats = {
                total: data.length,
                pending: 0, // 后端没有status字段
                inTransit: 0,
                delivered: 0
            };
            setStats(stats);

            message.success(`货物数据加载成功，共${data.length}条货物`);
        } catch (error) {
            message.error('获取货物数据失败');
            console.error('获取货物数据失败:', error);
            setShipments([]);
        } finally {
            setLoading(false);
        }
    };

    // 加载批次列表
    const loadBatchList = useCallback(async () => {
        try {
            const response = await uploadDataAPI.getBatchList(1, 100);
            setBatchList(response.records || []);
        } catch (error) {
            console.error('加载批次列表失败:', error);
        }
    }, []);

    // 处理批次选择
    const handleBatchSelect = (value) => {
        setDataId(value);
        if (value) {
            fetchShipments(value);
        }
    };

    // 处理手动输入dataId
    const handleSearch = () => {
        if (dataId) {
            fetchShipments(dataId);
        }
    };

    // 起点搜索处理
    const handleOriginSearch = () => {
        if (dataId) {
            fetchShipments(dataId);
        }
    };

    // 终点搜索处理
    const handleDestinationSearch = () => {
        if (dataId) {
            fetchShipments(dataId);
        }
    };


    // 导出数据
    const handleExport = () => {
        try {
            const csvContent = [
                ['货物ID', '原始ID', '起始节点', '目标节点', '需求量', '时间价值', '数据ID'],
                ...shipments.map(shipment => [
                    shipment.id,
                    shipment.shipment_id,
                    shipment.origin_node,
                    shipment.destination_node,
                    shipment.demand,
                    shipment.time_value,
                    shipment.data_id,
                ])
            ].map(row => row.join(',')).join('\n');

            const blob = new Blob(['\uFEFF' + csvContent], {type: 'text/csv;charset=utf-8;'});
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', `货物数据_${new Date().toISOString().split('T')[0]}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            message.success('数据导出成功');
        } catch (error) {
            message.error('数据导出失败');
            console.error('数据导出失败:', error);
        }
    };

    // 页面加载时获取批次列表
    useEffect(() => {
        loadBatchList();
    }, [loadBatchList]);

    // 表格列定义
    const columns = [
        {
            title: '货物ID',
            dataIndex: 'id',
            key: 'id',
            width: 100,
            render: (text) => <span style={{fontWeight: 500}}>{text || '-'}</span>
        },
        {
            title: '原始ID',
            dataIndex: 'shipment_id',
            key: 'shipment_id',
            width: 100,
            render: (text) => text || '-'
        },
        {
            title: '起始节点',
            dataIndex: 'origin_node',
            key: 'origin_node',
            width: 100,
            render: (text) => {
                if (text === null || text === undefined) return '-';
                if (typeof text === 'object') return text.name || text.id || JSON.stringify(text);
                return String(text);
            }
        },
        {
            title: '目标节点',
            dataIndex: 'destination_node',
            key: 'destination_node',
            width: 100,
            render: (text) => {
                if (text === null || text === undefined) return '-';
                if (typeof text === 'object') return text.name || text.id || JSON.stringify(text);
                return String(text);
            }
        },
        {
            title: '需求量',
            dataIndex: 'demand',
            key: 'demand',
            width: 100,
            render: (text) => text || '-'
        },
        {
            title: '时间价值',
            dataIndex: 'time_value',
            key: 'time_value',
            width: 100,
            render: (text) => text || '-'
        },
        {
            title: '数据ID',
            dataIndex: 'data_id',
            key: 'data_id',
            width: 100,
            render: (text) => text || '-'
        },
        {
            title: '操作',
            key: 'actions',
            width: 120,
            render: (_, record) => (
                <div className="action-buttons">
                    <Button size="small" type="primary" ghost>
                        详情
                    </Button>
                </div>
            )
        }
    ];

    return (
        <div className="shipments-page">
            {/* 搜索栏 */}
            <Card className="search-section">
                <Row gutter={16} align="middle" wrap>
                    <Col>
                        <Select
                            placeholder="选择批次"
                            value={dataId}
                            onChange={handleBatchSelect}
                            style={{width: 200}}
                            allowClear
                        >
                            {batchList.map(batch => (
                                <Select.Option key={batch.dataId} value={batch.dataId}>
                                    批次{batch.dataId} - {batch.description || '无描述'}
                                </Select.Option>
                            ))}
                        </Select>
                    </Col>
                    <Col>
                        <Input
                            placeholder="或输入批次ID"
                            value={dataId}
                            onChange={(e) => setDataId(e.target.value)}
                            onPressEnter={handleSearch}
                            style={{width: 120}}
                        />
                    </Col>
                    <Col>
                        <Button
                            type="primary"
                            icon={<SearchOutlined/>}
                            onClick={handleSearch}
                            loading={loading}
                        >
                            查询
                        </Button>
                    </Col>
                    <Col>
                        <Input
                            placeholder="搜索起始节点..."
                            value={originSearch}
                            onChange={(e) => setOriginSearch(e.target.value)}
                            onPressEnter={handleOriginSearch}
                            style={{width: 200}}
                            allowClear
                        />
                    </Col>
                    <Col>
                        <Input
                            placeholder="搜索目标节点..."
                            value={destinationSearch}
                            onChange={(e) => setDestinationSearch(e.target.value)}
                            onPressEnter={handleDestinationSearch}
                            style={{width: 200}}
                            allowClear
                        />
                    </Col>
                    <Col>
                        <Button
                            type="primary"
                            onClick={fetchShipments}
                            loading={loading}
                            icon={<SearchOutlined/>}
                        >
                            搜索
                        </Button>
                    </Col>
                    <Col flex="auto"></Col>
                    <Col>
                        <Space>
                            <Button
                                icon={<ReloadOutlined/>}
                                onClick={fetchShipments}
                                loading={loading}
                                className="refresh-button"
                            >
                                刷新
                            </Button>
                            <Button
                                icon={<ExportOutlined/>}
                                onClick={handleExport}
                                className="export-button"
                            >
                                导出
                            </Button>
                        </Space>
                    </Col>
                </Row>
            </Card>

            {/* 统计信息 */}
            <Row gutter={16}>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="总货物数"
                            value={stats.total}
                            prefix="#"
                            valueStyle={{color: '#1890ff'}}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="起始节点数"
                            value={new Set(shipments.map(s => {
                                // 防御性编程：确保只使用数字或字符串
                                const node = s.origin_node;
                                if (node === null || node === undefined) return 0;
                                if (typeof node === 'object') return node.id || node.name || 0;
                                return Number(node);
                            })).size}
                            prefix="#"
                            valueStyle={{color: '#fa8c16'}}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="目标节点数"
                            value={new Set(shipments.map(s => {
                                // 防御性编程：确保只使用数字或字符串
                                const node = s.destination_node;
                                if (node === null || node === undefined) return 0;
                                if (typeof node === 'object') return node.id || node.name || 0;
                                return Number(node);
                            })).size}
                            prefix="#"
                            valueStyle={{color: '#1890ff'}}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="平均需求量"
                            value={shipments.length > 0 ? (shipments.reduce((sum, s) => {
                                const demand = s.demand;
                                if (demand === null || demand === undefined) return sum;
                                if (typeof demand === 'object') return sum;
                                return sum + Number(demand);
                            }, 0) / shipments.length).toFixed(1) : 0}
                            prefix="#"
                            valueStyle={{color: '#52c41a'}}
                        />
                    </Card>
                </Col>
            </Row>

            {/* 货物列表 */}
            <Card title="货物列表">
                <Table
                    columns={columns}
                    dataSource={shipments}
                    rowKey="id"
                    loading={loading}
                    pagination={{
                        total: shipments.length,
                        pageSize: 10,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
                    }}
                    scroll={{x: 1200}}
                />
            </Card>
        </div>
    );
};

export default ShipmentsPage;